5 * Created on July 6, 2007
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
28 * A query action to get image information and upload history.
32 class ApiQueryImageInfo
extends ApiQueryBase
{
33 const TRANSFORM_LIMIT
= 50;
34 private static $transformCount = 0;
36 public function __construct( $query, $moduleName, $prefix = 'ii' ) {
37 // We allow a subclass to override the prefix, to create a related API module.
38 // Some other parts of MediaWiki construct this with a null $prefix, which used to be ignored when this only took two arguments
39 if ( is_null( $prefix ) ) {
42 parent
::__construct( $query, $moduleName, $prefix );
45 public function execute() {
46 $params = $this->extractRequestParams();
48 $prop = array_flip( $params['prop'] );
50 $scale = $this->getScale( $params );
52 $metadataOpts = array(
53 'version' => $params['metadataversion'],
56 $pageIds = $this->getPageSet()->getAllTitlesByNamespace();
57 if ( !empty( $pageIds[NS_FILE
] ) ) {
58 $titles = array_keys( $pageIds[NS_FILE
] );
59 asort( $titles ); // Ensure the order is always the same
62 if ( !is_null( $params['continue'] ) ) {
63 $cont = explode( '|', $params['continue'] );
64 $this->dieContinueUsageIf( count( $cont ) != 2 );
65 $fromTitle = strval( $cont[0] );
66 $fromTimestamp = $cont[1];
67 // Filter out any titles before $fromTitle
68 foreach ( $titles as $key => $title ) {
69 if ( $title < $fromTitle ) {
70 unset( $titles[$key] );
77 $result = $this->getResult();
78 //search only inside the local repo
79 if ( $params['localonly'] ) {
80 $images = RepoGroup
::singleton()->getLocalRepo()->findFiles( $titles );
82 $images = RepoGroup
::singleton()->findFiles( $titles );
84 foreach ( $titles as $title ) {
85 $pageId = $pageIds[NS_FILE
][$title];
86 $start = $title === $fromTitle ?
$fromTimestamp : $params['start'];
88 if ( !isset( $images[$title] ) ) {
89 if ( isset( $prop['uploadwarning'] ) ) {
90 // Uploadwarning needs info about non-existing files
91 $images[$title] = wfLocalFile( $title );
94 array( 'query', 'pages', intval( $pageId ) ),
97 // The above can't fail because it doesn't increase the result size
102 /** @var $img File */
103 $img = $images[$title];
105 if ( self
::getTransformCount() >= self
::TRANSFORM_LIMIT
) {
106 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
107 // See the 'the user is screwed' comment below
108 $this->setContinueEnumParameter( 'start',
109 $start !== null ?
$start : wfTimestamp( TS_ISO_8601
, $img->getTimestamp() )
112 $this->setContinueEnumParameter( 'continue',
113 $this->getContinueStr( $img, $start ) );
118 $fit = $result->addValue(
119 array( 'query', 'pages', intval( $pageId ) ),
120 'imagerepository', $img->getRepoName()
123 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
124 // The user is screwed. imageinfo can't be solely
125 // responsible for exceeding the limit in this case,
126 // so set a query-continue that just returns the same
127 // thing again. When the violating queries have been
128 // out-continued, the result will get through
129 $this->setContinueEnumParameter( 'start',
130 $start !== null ?
$start : wfTimestamp( TS_ISO_8601
, $img->getTimestamp() )
133 $this->setContinueEnumParameter( 'continue',
134 $this->getContinueStr( $img, $start ) );
139 // Check if we can make the requested thumbnail, and get transform parameters.
140 $finalThumbParams = $this->mergeThumbParams( $img, $scale, $params['urlparam'] );
142 // Get information about the current version first
143 // Check that the current version is within the start-end boundaries
146 ( is_null( $start ) ||
$img->getTimestamp() <= $start ) &&
147 ( is_null( $params['end'] ) ||
$img->getTimestamp() >= $params['end'] )
151 $fit = $this->addPageSubItem( $pageId,
152 self
::getInfo( $img, $prop, $result,
153 $finalThumbParams, $metadataOpts
157 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
158 // See the 'the user is screwed' comment above
159 $this->setContinueEnumParameter( 'start',
160 wfTimestamp( TS_ISO_8601
, $img->getTimestamp() ) );
162 $this->setContinueEnumParameter( 'continue',
163 $this->getContinueStr( $img ) );
169 // Now get the old revisions
170 // Get one more to facilitate query-continue functionality
171 $count = ( $gotOne ?
1 : 0 );
172 $oldies = $img->getHistory( $params['limit'] - $count +
1, $start, $params['end'] );
173 /** @var $oldie File */
174 foreach ( $oldies as $oldie ) {
175 if ( ++
$count > $params['limit'] ) {
176 // We've reached the extra one which shows that there are additional pages to be had. Stop here...
177 // Only set a query-continue if there was only one title
178 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
179 $this->setContinueEnumParameter( 'start',
180 wfTimestamp( TS_ISO_8601
, $oldie->getTimestamp() ) );
184 $fit = self
::getTransformCount() < self
::TRANSFORM_LIMIT
&&
185 $this->addPageSubItem( $pageId,
186 self
::getInfo( $oldie, $prop, $result,
187 $finalThumbParams, $metadataOpts
191 if ( count( $pageIds[NS_FILE
] ) == 1 ) {
192 $this->setContinueEnumParameter( 'start',
193 wfTimestamp( TS_ISO_8601
, $oldie->getTimestamp() ) );
195 $this->setContinueEnumParameter( 'continue',
196 $this->getContinueStr( $oldie ) );
209 * From parameters, construct a 'scale' array
210 * @param array $params Parameters passed to api.
211 * @return Array or Null: key-val array of 'width' and 'height', or null
213 public function getScale( $params ) {
214 $p = $this->getModulePrefix();
216 if ( $params['urlwidth'] != -1 ) {
218 $scale['width'] = $params['urlwidth'];
219 $scale['height'] = $params['urlheight'];
220 } elseif ( $params['urlheight'] != -1 ) {
221 // Height is specified but width isn't
222 // Don't set $scale['width']; this signals mergeThumbParams() to fill it with the image's width
224 $scale['height'] = $params['urlheight'];
227 if ( $params['urlparam'] ) {
228 $this->dieUsage( "{$p}urlparam requires {$p}urlwidth", "urlparam_no_width" );
235 /** Validate and merge scale parameters with handler thumb parameters, give error if invalid.
237 * We do this later than getScale, since we need the image
238 * to know which handler, since handlers can make their own parameters.
239 * @param File $image Image that params are for.
240 * @param array $thumbParams thumbnail parameters from getScale
241 * @param string $otherParams of otherParams (iiurlparam).
242 * @return Array of parameters for transform.
244 protected function mergeThumbParams( $image, $thumbParams, $otherParams ) {
245 global $wgThumbLimits;
247 if ( !isset( $thumbParams['width'] ) && isset( $thumbParams['height'] ) ) {
248 // We want to limit only by height in this situation, so pass the
249 // image's full width as the limiting width. But some file types
250 // don't have a width of their own, so pick something arbitrary so
251 // thumbnailing the default icon works.
252 if ( $image->getWidth() <= 0 ) {
253 $thumbParams['width'] = max( $wgThumbLimits );
255 $thumbParams['width'] = $image->getWidth();
259 if ( !$otherParams ) {
262 $p = $this->getModulePrefix();
264 $h = $image->getHandler();
266 $this->setWarning( 'Could not create thumbnail because ' .
267 $image->getName() . ' does not have an associated image handler' );
271 $paramList = $h->parseParamString( $otherParams );
273 // Just set a warning (instead of dieUsage), as in many cases
274 // we could still render the image using width and height parameters,
275 // and this type of thing could happen between different versions of
277 $this->setWarning( "Could not parse {$p}urlparam for " . $image->getName()
278 . '. Using only width and height' );
282 if ( isset( $paramList['width'] ) ) {
283 if ( intval( $paramList['width'] ) != intval( $thumbParams['width'] ) ) {
284 $this->setWarning( "Ignoring width value set in {$p}urlparam ({$paramList['width']}) "
285 . "in favor of width value derived from {$p}urlwidth/{$p}urlheight ({$thumbParams['width']})" );
289 foreach ( $paramList as $name => $value ) {
290 if ( !$h->validateParam( $name, $value ) ) {
291 $this->dieUsage( "Invalid value for {$p}urlparam ($name=$value)", "urlparam" );
295 return $thumbParams +
$paramList;
299 * Get result information for an image revision
301 * @param $file File object
302 * @param array $prop of properties to get (in the keys)
303 * @param $result ApiResult object
304 * @param array $thumbParams containing 'width' and 'height' items, or null
305 * @param string|array $metadataOpts Options for metadata fetching.
306 * This is an array consisting of the keys:
307 * 'version': The metadata version for the metadata option
308 * @return Array: result array
310 static function getInfo( $file, $prop, $result, $thumbParams = null, $metadataOpts = false ) {
311 if ( !$metadataOpts ||
is_string( $metadataOpts ) ) {
312 $metadataOpts = array(
313 'version' => $metadataOpts ?
: 'latest',
316 $version = $metadataOpts['version'];
318 // Timestamp is shown even if the file is revdelete'd in interface
320 if ( isset( $prop['timestamp'] ) ) {
321 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $file->getTimestamp() );
324 $user = isset( $prop['user'] );
325 $userid = isset( $prop['userid'] );
327 if ( $user ||
$userid ) {
328 if ( $file->isDeleted( File
::DELETED_USER
) ) {
329 $vals['userhidden'] = '';
332 $vals['user'] = $file->getUser();
335 $vals['userid'] = $file->getUser( 'id' );
337 if ( !$file->getUser( 'id' ) ) {
343 // This is shown even if the file is revdelete'd in interface
345 if ( isset( $prop['size'] ) ||
isset( $prop['dimensions'] ) ) {
346 $vals['size'] = intval( $file->getSize() );
347 $vals['width'] = intval( $file->getWidth() );
348 $vals['height'] = intval( $file->getHeight() );
350 $pageCount = $file->pageCount();
351 if ( $pageCount !== false ) {
352 $vals['pagecount'] = $pageCount;
356 $pcomment = isset( $prop['parsedcomment'] );
357 $comment = isset( $prop['comment'] );
359 if ( $pcomment ||
$comment ) {
360 if ( $file->isDeleted( File
::DELETED_COMMENT
) ) {
361 $vals['commenthidden'] = '';
364 $vals['parsedcomment'] = Linker
::formatComment(
365 $file->getDescription(), $file->getTitle() );
368 $vals['comment'] = $file->getDescription();
373 $url = isset( $prop['url'] );
374 $sha1 = isset( $prop['sha1'] );
375 $meta = isset( $prop['metadata'] );
376 $extmetadata = isset( $prop['extmetadata'] );
377 $mime = isset( $prop['mime'] );
378 $mediatype = isset( $prop['mediatype'] );
379 $archive = isset( $prop['archivename'] );
380 $bitdepth = isset( $prop['bitdepth'] );
381 $uploadwarning = isset( $prop['uploadwarning'] );
383 if ( ( $url ||
$sha1 ||
$meta ||
$mime ||
$mediatype ||
$archive ||
$bitdepth )
384 && $file->isDeleted( File
::DELETED_FILE
) ) {
385 $vals['filehidden'] = '';
387 //Early return, tidier than indenting all following things one level
392 if ( !is_null( $thumbParams ) ) {
393 $mto = $file->transform( $thumbParams );
394 self
::$transformCount++
;
395 if ( $mto && !$mto->isError() ) {
396 $vals['thumburl'] = wfExpandUrl( $mto->getUrl(), PROTO_CURRENT
);
398 // bug 23834 - If the URL's are the same, we haven't resized it, so shouldn't give the wanted
399 // thumbnail sizes for the thumbnail actual size
400 if ( $mto->getUrl() !== $file->getUrl() ) {
401 $vals['thumbwidth'] = intval( $mto->getWidth() );
402 $vals['thumbheight'] = intval( $mto->getHeight() );
404 $vals['thumbwidth'] = intval( $file->getWidth() );
405 $vals['thumbheight'] = intval( $file->getHeight() );
408 if ( isset( $prop['thumbmime'] ) && $file->getHandler() ) {
409 list( , $mime ) = $file->getHandler()->getThumbType(
410 $mto->getExtension(), $file->getMimeType(), $thumbParams );
411 $vals['thumbmime'] = $mime;
413 } elseif ( $mto && $mto->isError() ) {
414 $vals['thumberror'] = $mto->toText();
417 $vals['url'] = wfExpandUrl( $file->getFullURL(), PROTO_CURRENT
);
418 $vals['descriptionurl'] = wfExpandUrl( $file->getDescriptionUrl(), PROTO_CURRENT
);
422 $vals['sha1'] = wfBaseConvert( $file->getSha1(), 36, 16, 40 );
426 wfSuppressWarnings();
427 $metadata = unserialize( $file->getMetadata() );
429 if ( $metadata && $version !== 'latest' ) {
430 $metadata = $file->convertMetadataVersion( $metadata, $version );
432 $vals['metadata'] = $metadata ? self
::processMetaData( $metadata, $result ) : null;
435 if ( $extmetadata ) {
436 // Note, this should return an array where all the keys
437 // start with a letter, and all the values are strings.
438 // Thus there should be no issue with format=xml.
439 $format = new FormatMetadata
;
440 $extmetaArray = $format->fetchExtendedMetadata( $file );
441 $vals['extmetadata'] = $extmetaArray;
445 $vals['mime'] = $file->getMimeType();
449 $vals['mediatype'] = $file->getMediaType();
452 if ( $archive && $file->isOld() ) {
453 $vals['archivename'] = $file->getArchiveName();
457 $vals['bitdepth'] = $file->getBitDepth();
460 if ( $uploadwarning ) {
461 $vals['html'] = SpecialUpload
::getExistsWarning( UploadBase
::getExistsWarning( $file ) );
468 * Get the count of image transformations performed
470 * If this is >= TRANSFORM_LIMIT, you should probably stop processing images.
472 * @return integer count
474 static function getTransformCount() {
475 return self
::$transformCount;
480 * @param $metadata Array
481 * @param $result ApiResult
484 public static function processMetaData( $metadata, $result ) {
486 if ( is_array( $metadata ) ) {
487 foreach ( $metadata as $key => $value ) {
488 $r = array( 'name' => $key );
489 if ( is_array( $value ) ) {
490 $r['value'] = self
::processMetaData( $value, $result );
492 $r['value'] = $value;
497 $result->setIndexedTagName( $retval, 'metadata' );
501 public function getCacheMode( $params ) {
507 * @param null|string $start
510 protected function getContinueStr( $img, $start = null ) {
511 if ( $start === null ) {
512 $start = $img->getTimestamp();
514 return $img->getOriginalTitle()->getDBkey() . '|' . $start;
517 public function getAllowedParams() {
520 ApiBase
::PARAM_ISMULTI
=> true,
521 ApiBase
::PARAM_DFLT
=> 'timestamp|user',
522 ApiBase
::PARAM_TYPE
=> self
::getPropertyNames()
525 ApiBase
::PARAM_TYPE
=> 'limit',
526 ApiBase
::PARAM_DFLT
=> 1,
527 ApiBase
::PARAM_MIN
=> 1,
528 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
529 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
532 ApiBase
::PARAM_TYPE
=> 'timestamp'
535 ApiBase
::PARAM_TYPE
=> 'timestamp'
538 ApiBase
::PARAM_TYPE
=> 'integer',
539 ApiBase
::PARAM_DFLT
=> -1
541 'urlheight' => array(
542 ApiBase
::PARAM_TYPE
=> 'integer',
543 ApiBase
::PARAM_DFLT
=> -1
545 'metadataversion' => array(
546 ApiBase
::PARAM_TYPE
=> 'string',
547 ApiBase
::PARAM_DFLT
=> '1',
550 ApiBase
::PARAM_DFLT
=> '',
551 ApiBase
::PARAM_TYPE
=> 'string',
554 'localonly' => false,
559 * Returns all possible parameters to iiprop
561 * @param array $filter List of properties to filter out
565 public static function getPropertyNames( $filter = array() ) {
566 return array_diff( array_keys( self
::getProperties() ), $filter );
570 * Returns array key value pairs of properties and their descriptions
572 * @param string $modulePrefix
575 private static function getProperties( $modulePrefix = '' ) {
577 'timestamp' => ' timestamp - Adds timestamp for the uploaded version',
578 'user' => ' user - Adds the user who uploaded the image version',
579 'userid' => ' userid - Add the user ID that uploaded the image version',
580 'comment' => ' comment - Comment on the version',
581 'parsedcomment' => ' parsedcomment - Parse the comment on the version',
582 'url' => ' url - Gives URL to the image and the description page',
583 'size' => ' size - Adds the size of the image in bytes and the height, width and page count (if applicable)',
584 'dimensions' => ' dimensions - Alias for size', // For backwards compatibility with Allimages
585 'sha1' => ' sha1 - Adds SHA-1 hash for the image',
586 'mime' => ' mime - Adds MIME type of the image',
587 'thumbmime' => ' thumbmime - Adds MIME type of the image thumbnail' .
588 ' (requires url and param ' . $modulePrefix . 'urlwidth)',
589 'mediatype' => ' mediatype - Adds the media type of the image',
590 'metadata' => ' metadata - Lists Exif metadata for the version of the image',
591 'extmetadata' => ' extmetadata - Lists formatted metadata combined from multiple sources. Results are HTML formatted.',
592 'archivename' => ' archivename - Adds the file name of the archive version for non-latest versions',
593 'bitdepth' => ' bitdepth - Adds the bit depth of the version',
594 'uploadwarning' => ' uploadwarning - Used by the Special:Upload page to get information about an existing file. Not intended for use outside MediaWiki core',
599 * Returns the descriptions for the properties provided by getPropertyNames()
601 * @param array $filter List of properties to filter out
602 * @param string $modulePrefix
605 public static function getPropertyDescriptions( $filter = array(), $modulePrefix = '' ) {
607 array( 'What image information to get:' ),
608 array_values( array_diff_key( self
::getProperties( $modulePrefix ), array_flip( $filter ) ) )
613 * Return the API documentation for the parameters.
614 * @return Array parameter documentation.
616 public function getParamDescription() {
617 $p = $this->getModulePrefix();
619 'prop' => self
::getPropertyDescriptions( array(), $p ),
620 'urlwidth' => array( "If {$p}prop=url is set, a URL to an image scaled to this width will be returned.",
621 'For performance reasons if this option is used, ' .
622 'no more than ' . self
::TRANSFORM_LIMIT
. ' scaled images will be returned.' ),
623 'urlheight' => "Similar to {$p}urlwidth.",
624 'urlparam' => array( "A handler specific parameter string. For example, pdf's ",
625 "might use 'page15-100px'. {$p}urlwidth must be used and be consistent with {$p}urlparam" ),
626 'limit' => 'How many image revisions to return per image',
627 'start' => 'Timestamp to start listing from',
628 'end' => 'Timestamp to stop listing at',
629 'metadataversion' => array( "Version of metadata to use. if 'latest' is specified, use latest version.",
630 "Defaults to '1' for backwards compatibility" ),
631 'continue' => 'If the query response includes a continue value, use it here to get another page of results',
632 'localonly' => 'Look only for files in the local repository',
636 public static function getResultPropertiesFiltered( $filter = array() ) {
638 'timestamp' => array(
639 'timestamp' => 'timestamp'
642 'userhidden' => 'boolean',
647 'userhidden' => 'boolean',
648 'userid' => 'integer',
653 'width' => 'integer',
654 'height' => 'integer',
655 'pagecount' => array(
656 ApiBase
::PROP_TYPE
=> 'integer',
657 ApiBase
::PROP_NULLABLE
=> true
660 'dimensions' => array(
662 'width' => 'integer',
663 'height' => 'integer',
664 'pagecount' => array(
665 ApiBase
::PROP_TYPE
=> 'integer',
666 ApiBase
::PROP_NULLABLE
=> true
670 'commenthidden' => 'boolean',
672 ApiBase
::PROP_TYPE
=> 'string',
673 ApiBase
::PROP_NULLABLE
=> true
676 'parsedcomment' => array(
677 'commenthidden' => 'boolean',
678 'parsedcomment' => array(
679 ApiBase
::PROP_TYPE
=> 'string',
680 ApiBase
::PROP_NULLABLE
=> true
684 'filehidden' => 'boolean',
686 ApiBase
::PROP_TYPE
=> 'string',
687 ApiBase
::PROP_NULLABLE
=> true
689 'thumbwidth' => array(
690 ApiBase
::PROP_TYPE
=> 'integer',
691 ApiBase
::PROP_NULLABLE
=> true
693 'thumbheight' => array(
694 ApiBase
::PROP_TYPE
=> 'integer',
695 ApiBase
::PROP_NULLABLE
=> true
697 'thumberror' => array(
698 ApiBase
::PROP_TYPE
=> 'string',
699 ApiBase
::PROP_NULLABLE
=> true
702 ApiBase
::PROP_TYPE
=> 'string',
703 ApiBase
::PROP_NULLABLE
=> true
705 'descriptionurl' => array(
706 ApiBase
::PROP_TYPE
=> 'string',
707 ApiBase
::PROP_NULLABLE
=> true
711 'filehidden' => 'boolean',
713 ApiBase
::PROP_TYPE
=> 'string',
714 ApiBase
::PROP_NULLABLE
=> true
718 'filehidden' => 'boolean',
720 ApiBase
::PROP_TYPE
=> 'string',
721 ApiBase
::PROP_NULLABLE
=> true
724 'thumbmime' => array(
725 'filehidden' => 'boolean',
726 'thumbmime' => array(
727 ApiBase
::PROP_TYPE
=> 'string',
728 ApiBase
::PROP_NULLABLE
=> true
731 'mediatype' => array(
732 'filehidden' => 'boolean',
733 'mediatype' => array(
734 ApiBase
::PROP_TYPE
=> 'string',
735 ApiBase
::PROP_NULLABLE
=> true
738 'archivename' => array(
739 'filehidden' => 'boolean',
740 'archivename' => array(
741 ApiBase
::PROP_TYPE
=> 'string',
742 ApiBase
::PROP_NULLABLE
=> true
746 'filehidden' => 'boolean',
748 ApiBase
::PROP_TYPE
=> 'integer',
749 ApiBase
::PROP_NULLABLE
=> true
753 return array_diff_key( $props, array_flip( $filter ) );
756 public function getResultProperties() {
757 return self
::getResultPropertiesFiltered();
760 public function getDescription() {
761 return 'Returns image information and upload history';
764 public function getPossibleErrors() {
765 $p = $this->getModulePrefix();
766 return array_merge( parent
::getPossibleErrors(), array(
767 array( 'code' => "{$p}urlwidth", 'info' => "{$p}urlheight cannot be used without {$p}urlwidth" ),
768 array( 'code' => 'urlparam', 'info' => "Invalid value for {$p}urlparam" ),
769 array( 'code' => 'urlparam_no_width', 'info' => "{$p}urlparam requires {$p}urlwidth" ),
773 public function getExamples() {
775 'api.php?action=query&titles=File:Albert%20Einstein%20Head.jpg&prop=imageinfo',
776 'api.php?action=query&titles=File:Test.jpg&prop=imageinfo&iilimit=50&iiend=20071231235959&iiprop=timestamp|user|url',
780 public function getHelpUrls() {
781 return 'https://www.mediawiki.org/wiki/API:Properties#imageinfo_.2F_ii';